﻿using System.ServiceModel.Channels;
using System.Xml;

namespace WDA.Core.DynamicReconfiguration
{
   public sealed class ConfigVersionHeader : MessageHeader
   {
      private const string NAME = "ConfigVersion";
      private const string NAMESPACE = "http://vsoft.pl/WDAB";

      private readonly long _version;

      public ConfigVersionHeader(long version)
      {
         _version = version;
      }
      public long VersionNumber
      {
         get { return _version; }
      }

      protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
      {
         writer.WriteValue(_version);
      }

      public static ConfigVersionHeader ReadFrom(Message message)
      {
         ConfigVersionHeader result;
         int index = message.Headers.FindHeader(NAME, NAMESPACE);
         if (index < 0)
         {
            return null;
         }
         using (XmlDictionaryReader readerAtHeader = message.Headers.GetReaderAtHeader(index))
         {
            result = ReadFrom(readerAtHeader);
         }
         MessageHeaderInfo headerInfo = message.Headers[index];
         if (!message.Headers.UnderstoodHeaders.Contains(headerInfo))
         {
            message.Headers.UnderstoodHeaders.Add(headerInfo);
         }
         return result;
      }

      public static ConfigVersionHeader ReadFrom(XmlDictionaryReader reader)
      {
         reader.ReadStartElement(NAME, NAMESPACE);
         ConfigVersionHeader result = new ConfigVersionHeader(long.Parse(reader.Value));
         reader.Read();
         reader.ReadEndElement();
         return result;
      }

      public override string Name
      {
         get { return NAME; }
      }
      public override string Namespace
      {
         get { return NAMESPACE; }
      }      
   }
}
